import { Injectable, BadRequestException, ForbiddenException, Logger } from '@nestjs/common'
import { DatabaseService } from '../../database/database.service'
import { UserRole } from '@prisma/client'
import * as bcrypt from 'bcrypt'

@Injectable()
export class UserService {
  private readonly logger = new Logger(UserService.name)

  constructor(private databaseService: DatabaseService) {}

  // 创建用户
  async createUser(createUserDto: any, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      // 权限检查：只有管理员和超级管理员可以创建用户
      if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限创建用户')
      }

      const { username, email, password, role = UserRole.USER } = createUserDto

      // 检查用户名是否已存在
      const existingUser = await this.databaseService.user.findFirst({
        where: {
          OR: [{ username }, { email }]
        }
      })

      if (existingUser) {
        throw new BadRequestException('用户名或邮箱已存在')
      }

      // 权限检查：不能创建比自己权限高的用户
      this.checkPermission(currentUser.role as UserRole, role, '创建')

      // 加密密码
      const hashedPassword = await bcrypt.hash(password, 10)

      const user = await this.databaseService.user.create({
        data: {
          username,
          email,
          password: hashedPassword,
          role,
          isActive: true
        }
      })

      this.logger.log(`User ${currentUser.username} created user ${user.username}`, 'UserService')

      // 返回用户信息（不包含密码）
      const { password: _, ...userWithoutPassword } = user
      return {
        message: '用户创建成功',
        user: userWithoutPassword
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to create user: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('创建用户失败')
    }
  }

  // 获取用户列表
  async getUsers(query: any, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      // 权限检查：只有管理员和超级管理员可以查看用户列表
      if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限查看用户列表')
      }

      const { page = 1, limit = 10, search, role, isActive } = query
      const skip = (page - 1) * limit

      const where: any = {}

      if (search) {
        where.OR = [{ username: { contains: search } }, { email: { contains: search } }]
      }

      if (role) {
        where.role = role
      }

      if (isActive !== undefined) {
        where.isActive = isActive === 'true'
      }

      const [users, total] = await Promise.all([
        this.databaseService.user.findMany({
          where,
          select: {
            id: true,
            username: true,
            email: true,
            role: true,
            isActive: true,
            createdAt: true,
            updatedAt: true,
            lastLoginAt: true,
            emailVerifiedAt: true
          },
          orderBy: {
            createdAt: 'desc'
          },
          skip,
          take: parseInt(limit)
        }),
        this.databaseService.user.count({ where })
      ])

      return {
        users,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit)
        }
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to get users: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('获取用户列表失败')
    }
  }

  // 获取单个用户
  async getUserById(id: string, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      const user = await this.databaseService.user.findUnique({
        where: { id },
        select: {
          id: true,
          username: true,
          email: true,
          role: true,
          isActive: true,
          createdAt: true,
          updatedAt: true,
          lastLoginAt: true,
          emailVerifiedAt: true
        }
      })

      if (!user) {
        throw new BadRequestException('用户不存在')
      }

      // 权限检查：用户只能查看自己的信息，管理员可以查看所有用户
      if (currentUser.id !== id && ![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限查看该用户信息')
      }

      return { user }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to get user: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('获取用户信息失败')
    }
  }

  async findById(id: string, currentUser: any): Promise<any> {
    return this.getUserById(id, currentUser.id)
  }

  async update(id: string, updateData: any, currentUserId: string): Promise<any> {
    const user = await this.databaseService.user.update({
      where: { id },
      data: updateData
    })
    return user
  }

  async uploadAvatar(userId: string, file: any): Promise<string> {
    // 简单实现，返回一个模拟的URL
    return `https://example.com/avatars/${userId}.jpg`
  }

  async getStats(): Promise<any> {
    const totalUsers = await this.databaseService.user.count()
    const activeUsers = await this.databaseService.user.count({
      where: { isActive: true }
    })
    return {
      total: totalUsers,
      active: activeUsers,
      inactive: totalUsers - activeUsers
    }
  }

  async create(createUserDto: any, currentUserId: string): Promise<any> {
    const user = await this.databaseService.user.create({
      data: {
        ...createUserDto,
        createdBy: currentUserId
      }
    })
    return user
  }

  async findAll(queryDto: any, currentUser: any): Promise<any> {
    const { page = 1, limit = 10, search, role, status } = queryDto
    const skip = (page - 1) * limit

    const where: any = {}
    if (search) {
      where.OR = [
        { username: { contains: search, mode: 'insensitive' } },
        { email: { contains: search, mode: 'insensitive' } }
      ]
    }
    if (role) where.role = role
    if (status !== undefined) where.isActive = status === 'active'

    const [users, total] = await Promise.all([
      this.databaseService.user.findMany({
        where,
        skip,
        take: limit,
        select: {
          id: true,
          username: true,
          email: true,
          role: true,
          isActive: true,
          createdAt: true,
          updatedAt: true
        },
        orderBy: { createdAt: 'desc' }
      }),
      this.databaseService.user.count({ where })
    ])

    return {
      data: users,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit)
    }
  }

  // 更新用户
  async updateUser(id: string, updateUserDto: any, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      const targetUser = await this.databaseService.user.findUnique({
        where: { id }
      })

      if (!targetUser) {
        throw new BadRequestException('目标用户不存在')
      }

      // 权限检查
      if (currentUser.id !== id) {
        this.checkPermission(currentUser.role as UserRole, targetUser.role as UserRole, '更新')
      }

      const { username, email, role, isActive } = updateUserDto
      const updateData: any = {}

      if (username && username !== targetUser.username) {
        const existingUser = await this.databaseService.user.findFirst({
          where: {
            username,
            id: { not: id }
          }
        })
        if (existingUser) {
          throw new BadRequestException('用户名已存在')
        }
        updateData.username = username
      }

      if (email && email !== targetUser.email) {
        const existingUser = await this.databaseService.user.findFirst({
          where: {
            email,
            id: { not: id }
          }
        })
        if (existingUser) {
          throw new BadRequestException('邮箱已存在')
        }
        updateData.email = email
        updateData.emailVerifiedAt = null // 重置邮箱验证状态
      }

      if (role && role !== targetUser.role) {
        // 只有管理员可以修改角色
        if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
          throw new ForbiddenException('无权限修改用户角色')
        }
        this.checkPermission(currentUser.role as UserRole, role, '设置角色为')
        updateData.role = role
      }

      if (isActive !== undefined && isActive !== targetUser.isActive) {
        // 只有管理员可以修改用户状态
        if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
          throw new ForbiddenException('无权限修改用户状态')
        }
        updateData.isActive = isActive
      }

      if (Object.keys(updateData).length === 0) {
        return {
          message: '没有需要更新的内容',
          user: targetUser
        }
      }

      const updatedUser = await this.databaseService.user.update({
        where: { id },
        data: updateData,
        select: {
          id: true,
          username: true,
          email: true,
          role: true,
          isActive: true,
          createdAt: true,
          updatedAt: true,
          lastLoginAt: true,
          emailVerifiedAt: true
        }
      })

      this.logger.log(`User ${currentUser.username} updated user ${updatedUser.username}`, 'UserService')

      return {
        message: '用户更新成功',
        user: updatedUser
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to update user: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('更新用户失败')
    }
  }

  // 删除用户
  async deleteUser(id: string, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      if (currentUser.id === id) {
        throw new BadRequestException('不能删除自己')
      }

      const targetUser = await this.databaseService.user.findUnique({
        where: { id }
      })

      if (!targetUser) {
        throw new BadRequestException('目标用户不存在')
      }

      // 权限检查
      this.checkPermission(currentUser.role as UserRole, targetUser.role as UserRole, '删除')

      await this.databaseService.user.delete({
        where: { id }
      })

      this.logger.log(`User ${currentUser.username} deleted user ${targetUser.username}`, 'UserService')

      return {
        message: '用户删除成功'
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to delete user: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('删除用户失败')
    }
  }

  // 修改密码
  async changePassword(id: string, changePasswordDto: any, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      const targetUser = await this.databaseService.user.findUnique({
        where: { id }
      })

      if (!targetUser) {
        throw new BadRequestException('目标用户不存在')
      }

      // 权限检查：用户只能修改自己的密码，管理员可以修改其他用户密码
      if (currentUser.id !== id) {
        this.checkPermission(currentUser.role as UserRole, targetUser.role as UserRole, '修改密码')
      }

      const { oldPassword, newPassword } = changePasswordDto

      // 如果是修改自己的密码，需要验证旧密码
      if (currentUser.id === id) {
        const isOldPasswordValid = await bcrypt.compare(oldPassword, targetUser.password)
        if (!isOldPasswordValid) {
          throw new BadRequestException('旧密码错误')
        }
      }

      // 加密新密码
      const hashedNewPassword = await bcrypt.hash(newPassword, 10)

      await this.databaseService.user.update({
        where: { id },
        data: {
          password: hashedNewPassword
        }
      })

      this.logger.log(`User ${currentUser.username} changed password for user ${targetUser.username}`, 'UserService')

      return {
        message: '密码修改成功'
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to change password: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('修改密码失败')
    }
  }

  // 重置密码
  async resetPassword(id: string, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      const targetUser = await this.databaseService.user.findUnique({
        where: { id }
      })

      if (!targetUser) {
        throw new BadRequestException('目标用户不存在')
      }

      // 权限检查：只有管理员可以重置密码
      if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限重置密码')
      }

      this.checkPermission(currentUser.role as UserRole, targetUser.role as UserRole, '重置密码')

      // 生成默认密码
      const defaultPassword = '123456'
      const hashedPassword = await bcrypt.hash(defaultPassword, 10)

      await this.databaseService.user.update({
        where: { id },
        data: {
          password: hashedPassword
        }
      })

      this.logger.log(`User ${currentUser.username} reset password for user ${targetUser.username}`, 'UserService')

      return {
        message: '密码重置成功',
        defaultPassword
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to reset password: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('重置密码失败')
    }
  }

  // 获取用户统计信息
  async getUserStats(currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      // 权限检查：只有管理员可以查看统计信息
      if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限查看用户统计')
      }

      const [totalUsers, activeUsers, inactiveUsers, roleStats] = await Promise.all([
        this.databaseService.user.count(),
        this.databaseService.user.count({ where: { isActive: true } }),
        this.databaseService.user.count({ where: { isActive: false } }),
        this.databaseService.user.groupBy({
          by: ['role'],
          _count: {
            role: true
          }
        })
      ])

      const roleDistribution = roleStats.reduce(
        (acc, stat) => {
          acc[stat.role] = stat._count.role
          return acc
        },
        {} as Record<string, number>
      )

      return {
        totalUsers,
        activeUsers,
        inactiveUsers,
        roleDistribution
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to get user stats: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('获取用户统计失败')
    }
  }

  // 切换用户状态
  async toggleUserStatus(id: string, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      if (currentUser.id === id) {
        throw new BadRequestException('不能修改自己的状态')
      }

      const targetUser = await this.databaseService.user.findUnique({
        where: { id }
      })

      if (!targetUser) {
        throw new BadRequestException('目标用户不存在')
      }

      // 权限检查
      if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限修改用户状态')
      }

      this.checkPermission(currentUser.role as UserRole, targetUser.role as UserRole, '修改状态')

      const updatedUser = await this.databaseService.user.update({
        where: { id },
        data: {
          isActive: !targetUser.isActive
        },
        select: {
          id: true,
          username: true,
          email: true,
          role: true,
          isActive: true
        }
      })

      this.logger.log(
        `User ${currentUser.username} toggled status for user ${updatedUser.username} to ${updatedUser.isActive ? 'active' : 'inactive'}`,
        'UserService'
      )

      return {
        message: `用户状态已${updatedUser.isActive ? '激活' : '禁用'}`,
        user: updatedUser
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to toggle user status: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('修改用户状态失败')
    }
  }

  // 获取用户权限
  async getUserPermissions(userId: string, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      const targetUser = await this.databaseService.user.findUnique({
        where: { id: userId }
      })

      if (!targetUser) {
        throw new BadRequestException('目标用户不存在')
      }

      // 权限检查：用户可以查看自己的权限，管理员可以查看所有用户权限
      if (currentUser.id !== userId && ![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限查看该用户权限')
      }

      const permissions = this.getRolePermissions(targetUser.role as UserRole)

      return {
        user: {
          id: targetUser.id,
          username: targetUser.username,
          role: targetUser.role
        },
        permissions
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to get user permissions: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('获取用户权限失败')
    }
  }

  // 更新用户权限
  async updatePermissions(userId: string, updatePermissionsDto: any, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      const targetUser = await this.databaseService.user.findUnique({
        where: { id: userId }
      })

      if (!targetUser) {
        throw new BadRequestException('目标用户不存在')
      }

      // 权限检查：只有超级管理员可以更新权限
      if (currentUser.role !== UserRole.SUPER_ADMIN) {
        throw new ForbiddenException('无权限更新用户权限')
      }

      const { role } = updatePermissionsDto

      if (role && role !== targetUser.role) {
        this.checkPermission(currentUser.role as UserRole, role, '设置角色为')

        await this.databaseService.user.update({
          where: { id: userId },
          data: { role }
        })
      }

      const permissions = this.getRolePermissions(role || (targetUser.role as UserRole))

      this.logger.log(`User ${currentUser.username} updated permissions for user ${targetUser.username}`, 'UserService')

      return {
        message: '权限更新成功',
        user: {
          id: targetUser.id,
          username: targetUser.username,
          role: targetUser.role
        },
        permissions
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to update permissions: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('更新权限失败')
    }
  }

  // 导出用户数据
  async exportUsers(exportDto: any, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      // 只有管理员可以导出用户数据
      if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限导出用户数据')
      }

      const { format = 'csv', filters = {} } = exportDto

      const users = await this.databaseService.user.findMany({
        where: {
          ...filters
        },
        select: {
          id: true,
          username: true,
          email: true,
          role: true,
          isActive: true,
          createdAt: true,
          lastLoginAt: true
        },
        orderBy: {
          createdAt: 'desc'
        }
      })

      // 这里应该实现实际的导出逻辑（CSV、Excel等）
      const exportData = users.map(user => ({
        ID: user.id,
        用户名: user.username,
        邮箱: user.email,
        角色: user.role,
        状态: user.isActive ? '激活' : '禁用',
        创建时间: user.createdAt.toISOString(),
        最后登录: user.lastLoginAt?.toISOString() || '从未登录'
      }))

      this.logger.log(`User ${currentUser.username} exported ${users.length} users`, 'UserService')

      return {
        data: exportData,
        format,
        count: users.length,
        exportedAt: new Date()
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to export users: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('导出用户数据失败')
    }
  }

  // 导入用户数据
  async importUsers(file: any, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      // 只有超级管理员可以导入用户数据
      if (currentUser.role !== UserRole.SUPER_ADMIN) {
        throw new ForbiddenException('无权限导入用户数据')
      }

      // 这里应该实现实际的文件解析和用户创建逻辑
      // 由于没有具体的文件处理库，这里只是示例

      const results = {
        success: 0,
        failed: 0,
        errors: [] as string[]
      }

      // 示例：假设文件包含用户数据
      // const userData = await this.parseImportFile(file);
      // for (const user of userData) {
      //   try {
      //     await this.createUser(user, currentUserId);
      //     results.success++;
      //   } catch (error) {
      //     results.failed++;
      //     results.errors.push(`用户 ${user.username}: ${error.message}`);
      //   }
      // }

      this.logger.log(
        `User ${currentUser.username} imported users: ${results.success} success, ${results.failed} failed`,
        'UserService'
      )

      return {
        message: '用户导入完成',
        results,
        importedAt: new Date()
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to import users: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('导入用户数据失败')
    }
  }

  // 私有方法：获取角色权限
  private getRolePermissions(role: UserRole): string[] {
    const permissions: Record<UserRole, string[]> = {
      [UserRole.SUPER_ADMIN]: [
        'user.create',
        'user.read',
        'user.update',
        'user.delete',
        'user.manage_permissions',
        'content.create',
        'content.read',
        'content.update',
        'content.delete',
        'content.publish',
        'system.manage',
        'file.upload',
        'file.delete'
      ],
      [UserRole.ADMIN]: [
        'user.create',
        'user.read',
        'user.update',
        'content.create',
        'content.read',
        'content.update',
        'content.delete',
        'content.publish',
        'file.upload',
        'file.delete'
      ],
      [UserRole.EDITOR]: ['content.create', 'content.read', 'content.update', 'file.upload'],
      [UserRole.USER]: ['content.read']
    }

    return permissions[role] || []
  }

  // 删除用户
  async remove(id: string, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      // 权限检查：只有管理员和超级管理员可以删除用户
      if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限删除用户')
      }

      const targetUser = await this.databaseService.user.findUnique({
        where: { id }
      })

      if (!targetUser) {
        throw new BadRequestException('用户不存在')
      }

      // 不能删除自己
      if (id === currentUserId) {
        throw new BadRequestException('不能删除自己')
      }

      // 权限检查：不能删除比自己权限高的用户
      this.checkPermission(currentUser.role as UserRole, targetUser.role as UserRole, '删除')

      await this.databaseService.user.delete({
        where: { id }
      })

      this.logger.log(`User ${currentUser.username} deleted user ${targetUser.username}`, 'UserService')

      return { message: '用户删除成功' }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to delete user: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('删除用户失败')
    }
  }

  // 更新用户状态
  async updateStatus(id: string, status: boolean, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      // 权限检查：只有管理员和超级管理员可以更新用户状态
      if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限更新用户状态')
      }

      const targetUser = await this.databaseService.user.findUnique({
        where: { id }
      })

      if (!targetUser) {
        throw new BadRequestException('用户不存在')
      }

      // 不能修改自己的状态
      if (id === currentUserId) {
        throw new BadRequestException('不能修改自己的状态')
      }

      // 权限检查：不能修改比自己权限高的用户
      this.checkPermission(currentUser.role as UserRole, targetUser.role as UserRole, '修改状态')

      const user = await this.databaseService.user.update({
        where: { id },
        data: { isActive: status },
        select: {
          id: true,
          username: true,
          email: true,
          role: true,
          isActive: true,
          createdAt: true,
          updatedAt: true
        }
      })

      this.logger.log(
        `User ${currentUser.username} updated status of user ${targetUser.username} to ${status}`,
        'UserService'
      )

      return { message: '用户状态更新成功', user }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to update user status: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('更新用户状态失败')
    }
  }

  // 批量操作
  async batchOperation(batchDto: any, currentUserId: string) {
    try {
      const currentUser = await this.databaseService.user.findUnique({
        where: { id: currentUserId }
      })

      if (!currentUser) {
        throw new BadRequestException('当前用户不存在')
      }

      // 权限检查：只有管理员和超级管理员可以进行批量操作
      if (![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限进行批量操作')
      }

      const { operation, userIds } = batchDto
      const results = []

      for (const userId of userIds) {
        try {
          switch (operation) {
            case 'activate':
              await this.updateStatus(userId, true, currentUserId)
              results.push({ id: userId, success: true, message: '激活成功' })
              break
            case 'deactivate':
              await this.updateStatus(userId, false, currentUserId)
              results.push({ id: userId, success: true, message: '停用成功' })
              break
            case 'delete':
              await this.remove(userId, currentUserId)
              results.push({ id: userId, success: true, message: '删除成功' })
              break
            default:
              results.push({ id: userId, success: false, message: '不支持的操作' })
          }
        } catch (error) {
          results.push({ id: userId, success: false, message: error.message })
        }
      }

      return {
        message: '批量操作完成',
        results,
        summary: {
          total: userIds.length,
          success: results.filter(r => r.success).length,
          failed: results.filter(r => !r.success).length
        }
      }
    } catch (error) {
      if (error instanceof BadRequestException || error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to perform batch operation: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('批量操作失败')
    }
  }

  // 获取用户活动记录
  async getUserActivities(id: string, query: any, currentUser: any) {
    try {
      // 权限检查：用户只能查看自己的活动记录，管理员可以查看所有用户
      if (currentUser.id !== id && ![UserRole.ADMIN, UserRole.SUPER_ADMIN].includes(currentUser.role as any)) {
        throw new ForbiddenException('无权限查看该用户的活动记录')
      }

      const { page = 1, limit = 10 } = query
      const skip = (page - 1) * limit

      // 这里应该从实际的活动记录表中查询，暂时返回模拟数据
      const activities = []
      const total = 0

      return {
        activities,
        pagination: {
          page: parseInt(page),
          limit: parseInt(limit),
          total,
          pages: Math.ceil(total / limit)
        }
      }
    } catch (error) {
      if (error instanceof ForbiddenException) {
        throw error
      }
      this.logger.error(`Failed to get user activities: ${error.message}`, error.stack, 'UserService')
      throw new BadRequestException('获取用户活动记录失败')
    }
  }

  // 检查权限的辅助方法
  private checkPermission(currentUserRole: UserRole, targetRole: UserRole, operation: string) {
    const roleHierarchy = {
      [UserRole.USER]: 0,
      [UserRole.EDITOR]: 1,
      [UserRole.ADMIN]: 2,
      [UserRole.SUPER_ADMIN]: 3
    }

    if (roleHierarchy[currentUserRole] <= roleHierarchy[targetRole]) {
      throw new ForbiddenException(`无权限${operation}该角色的用户`)
    }
  }
}
